#ifndef TF_MODBUS_H
#define TF_MODBUS_H

#include <QDebug>
#include <QtSerialPort/qserialport.h>
#include <qeventloop.h>
#include <vector>
//#include "mainwindow.h"

#define MB_FUNC_WR_MULTI    0x10
#define MB_FUNC_WR_SINGLE   0x06
#define MB_FUNC_RD_HOLDING  0x03
#define MB_FUNC_WR_MULTI_REGS  0x10

typedef struct
{
#pragma pack(2)
    union
    {
        uint8_t buffer[4];
        struct
        {
            float    reg_flo;
            uint16_t reg_u16;
        } data;
    };

#pragma pack(2)

} DATA_TYPE_t;


class tf_modbus
{


public:
    tf_modbus();
    ~tf_modbus();

    enum {
        SerDev_Mid,
        SerDev_EPC_MFC,
        SerDev_TEC_0,   //new add for Purge Dehydrition
        SerDev_TEC_1,
        SerDev_TEC_2,
        SerDev_max
    };

//    enum {
//        SerDev_Mid,
//        SerDev_EPC,
//        SerDev_MFC,
//        SerDev_TEC,
//        SerDev_max
//    };

    bool tf_modbus_open(uint8_t whichUart, QString comPort);
    void tf_modbus_close(uint8_t whichUart);

    int serialWirte(uint8_t whichUart, unsigned char *buf,int buf_Len);
    int serialWirte(uint8_t whichUart, char *buf,int buf_Len); //LM add for chongzai
    void delay(int mSec);

        /*
            uiButtonConnectStus: 0 conncet   1: disconncet
            comPort: com name, such as COM1
        */
    bool tf_modbusDeviceHandle(uint8_t whichUart, bool isUiButtonConnect, QString comPort); //true: opened   false: open failure

    quint16 sendReadHoldingReg(uint8_t whichUart,quint8 slaveID, quint16 serverAddr);
    float sendReadFloatReg(uint8_t whichUart,quint8 slaveID, quint16 serverAddr);
    void  sendWriteHoldingReg(uint8_t whichUart,quint8 slaveID, quint16 serverAddr, quint16 value);
    void  sendWriteMultiHoldingReg(uint8_t whichUart,quint8 slaveID,uint16_t *writeBuf, quint16 serverAddr, quint16 reg_quantity);
    //void  sendReadRequest(uint8_t whichUart,QVector<quint16> &buf,quint16 startAddr, qint16 registerNum);
    void  sendWriteRequest();
    void sendWriteFloatReg(uint8_t whichUart, quint8 slaveID, quint16 serverAddr, float value);
    int sendReadMultiFloatReg(uint8_t whichUart,quint8 slaveID,float *readBuf, quint16 serverAddr, quint16 reg_num);
protected:
   // QSerialPort *SerDevice[SerDev_max] ={nullptr};
    std::shared_ptr<QSerialPort> SerDevice[SerDev_max];
   // std::shared_ptr<QSerialPort> std::vector<QSerialPort>SerDevice;


private:
    bool uiButtonConnectStus = false; //false: Not connect   true:connect
    //QString hexString2QString( uint8_t *buff, int16_t len);
    // QSerialPort *uart_device=nullptr;


    static const quint16 modbus_crc16_table[256];
    quint16  mb_crc16(unsigned char *crcBuf, int nSize);

};

#endif // TF_MODBUS_H
